<template>
  <div>
    <Form
      :model="modelForm"
      ref="editForm"
      class="ivu-form-no-margin-bottom"
      :rules="rule"
      :label-width="130"
    >
      <Form-item prop="appId" :label="$t('module.routeManage.application')">
        <Select transfer v-model.trim="modelForm.appId" :placeholder="$t('module.routeManage.placeholder.application')">
          <Option
            v-for="(item) in applicationIdList"
            :value="item.clientId"
            :key="item.clientId"
          >{{ item.appName }}</Option>
        </Select>
      </Form-item>
      <Form-item :prop="serviceIdOrUrl" :label="$t('module.routeManage.serverNameOrUrlProxy')">
        <div style="display:flex;">
          <Select
            v-model="serviceOrUrl"
            style="width: 150px;"
            transfer
            
            @on-change="changeServiceOrUrl"
          >
            <Option v-for="item in routeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
          <Input
            v-show="serviceOrUrl == '0'"
            v-model.trim="modelForm.serviceId"
            :placeholder="$t('module.routeManage.placeholder.serverName')"
            :maxlength="50"
          ></Input>
          <Input
            v-show="serviceOrUrl == '1'"
            v-model.trim="modelForm.url"
            :placeholder="$t('module.routeManage.placeholder.urlProxy')"
            :maxlength="50"
          ></Input>
        </div>
      </Form-item>
      <Form-item prop="groupName" :required="isRequired" :label="$t('module.routeManage.groupname')" v-if="serviceOrUrl == '0'">
        <Input
          v-model.trim="modelForm.groupName"
          :placeholder="$t('module.routeManage.placeholder.groupname')"
          :maxlength="50"
        ></Input>
      </Form-item>
      <Form-item prop="path" :label="$t('module.routeManage.path')">
        <template slot="label">
          <span>{{$t('module.routeManage.path')}}</span>
          <Tooltip :content="$t('module.routeManage.tip.path')" placement="top-start" max-width="300">
            <Icon type="md-help-circle"/>
          </Tooltip>
        </template>
        <Input v-model.trim="modelForm.path" :placeholder="$t('module.routeManage.placeholder.path')" :maxlength="50"></Input>
      </Form-item>
      <Form-item prop="stripPrefix" :label="$t('module.routeManage.stripPrefix')">
        <template slot="label">
          <span>{{$t('module.routeManage.stripPrefix')}}</span>
          <Tooltip :content="$t('module.routeManage.tip.stripPrefix')" placement="top-start" max-width="300">
            <Icon type="md-help-circle"/>
          </Tooltip>
        </template>
        <InputNumber
          :max="10"
          :min="0"
          :step="1"
          v-model="modelForm.stripPrefix"
          @on-change="changePrefix"
          style="width:100%;"
        ></InputNumber>
      </Form-item>
      <Form-item prop="routeType" :label="$t('module.routeManage.routeType')">
        <Select transfer v-model.trim="modelForm.routeType" :placeholder="$t('module.routeManage.placeholder.routeType')">
          <Option
            :value="item.vsiKey"
            :key="index"
            v-for="(item, index) in valueSet.gateway_route_type"
          >{{ item.vsiValue }}</Option>
        </Select>
      </Form-item>
      <Form-item prop="retryable" :label="$t('module.routeManage.retryable')">
        <Select transfer v-model.trim="modelForm.retryable" :placeholder="$t('module.routeManage.placeholder.retryable')">
          <Option value="1">{{$t('common.yes')}}</Option>
          <Option value="0">{{$t('common.no')}}</Option>
        </Select>
      </Form-item>
      <Form-item prop="enabled" :label="$t('module.routeManage.enabled')">
        <Select transfer v-model.trim="modelForm.enabled" :placeholder="$t('module.routeManage.placeholder.enabled')">
          <Option value="1">{{$t('common.yes')}}</Option>
          <Option value="0">{{$t('common.no')}}</Option>
        </Select>
      </Form-item>
    </Form>
  </div>
</template>
<script>
import { debounce } from "./index.js";
import locales from "./locales.js";
export default {
  components: {},
  mixins: [locales],
  props: {
    valueSet: Object,
    row: {
      type: Object,
      default() {
        return {};
      }
    },
    isAdd: Boolean
  },
  data() {
    const checkId = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error(this.$t("module.routeManage.enterid")));
      }
      callback();
    };
    const checkServerId = (rule, value, callback) => {
      let reg = /^[a-zA-Z]{1,}([0-9a-zA-Z-]){0,}$/;
      if (value.trim() === "") {
        callback(new Error(this.$t("module.routeManage.enterserverid")));
      } else if (!reg.test(value)) {
        callback(new Error(this.$t("module.routeManage.validaserverid")));
      }
      callback();
    };
    const checkUrl = (rule, value, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (value.trim() === "") {
        callback(new Error(this.$t("module.routeManage.enterurl")));
      } else if (!reg.test(value)) {
        callback(new Error(this.$t("module.routeManage.validatorurl")));
      }
      callback();
    };
    const checkgroupName = (rule, value, callback) => {
      if (value.trim() === "" && this.serviceOrUrl === "0") {
        callback(new Error(this.$t("module.routeManage.warning.groupname")));
      }
      callback();
    };
    const checkAppId = (rule, value, callback) => {
      if (value.trim() === "") {
        callback(new Error(this.$t("module.routeManage.warning.application")));
      }
      callback();
    };

    return {
      fun: null,
      applicationIdList: [],
      routeList: [
        {
          id: "0",
          name: this.$t("module.routeManage.serviceId")
        },
        {
          id: "1",
          name: this.$t("module.routeManage.url")
        }
      ],
      serviceOrUrl: "1",
      serviceIdOrUrl: "url",
      isRequired: true,
      modelForm: {
        tenantCode: $store.state["ripples-components"].userInfo.tenantCode,
        appId: "",
        groupName: "",
        id: "",
        path: "",
        serviceId: "",
        url: "",
        stripPrefix: 0,
        retryable: "",
        enabled: "",
        gatewayType: "",
        routeType: "",
        receiveType: "",
        sendType: ""
      },
      rule: {
        serviceId: [{ required: true, validator: checkServerId, trigger: "blur" }],
        appId: [{ required: true, validator: checkAppId, trigger: "blur" }],
        url: [{ required: true, validator: checkUrl, trigger: "blur" }],
        id: [{ required: true, validator: checkId, trigger: "blur" }],
        path: [{ required: true, message: this.$t("module.routeManage.warning.path"), trigger: "blur" }],
        retryable: [{ required: true, message: this.$t("module.routeManage.warning.retryable"), trigger: "change" }],
        enabled: [{ required: true, message: this.$t("module.routeManage.warning.enabled"), trigger: "change" }],
        stripPrefix: [{ required: true, message: this.$t("module.routeManage.warning.stripPrefix"), type: "number", trigger: "blur" }],
        groupName: [{ validator: checkgroupName, trigger: "blur" }]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          loading: false,
          handle: () => {
            this.save();
          }
        },
        {
          text: this.$t("common.cancel"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  created: function() {
    if (this.row.id) {
      this.$emit("SetTitle",this.$t("module.routeManage.title.editRoute"));
    } else {
      this.$emit("SetTitle", this.$t("module.routeManage.title.addRoute"));
    }
    this.$emit("SetPageWidth", 700);
    this.setPageButton();
    this.getApplicationByTenantCode();
    this.init();
  },
  mounted: function() {},
  methods: {
    getApplicationByTenantCode() {
      this.$store.dispatch("getApplicationByTenantCode", { tenantCode: this.modelForm.tenantCode }).then(response => {
        this.applicationIdList = response.data;
      });
    },
    debounce(fn, wait = 300) {
      if (this.fun !== null) {
        clearTimeout(this.fun);
      }
      this.fun = setTimeout(fn, wait);
    },
    changePrefix(value) {
      this.debounce(() => {
        this.handlePrefix(value);
      }, 300);
    },
    handlePrefix(value) {
      if (String(value).indexOf(".") > 0) {
        this.modelForm.stripPrefix = parseInt(value);
      }
    },
    init() {
      if (!this.isAdd) {
        this.row.stripPrefix = parseInt(this.row.stripPrefix);
        this.modelForm = Object.assign(this.modelForm, this.row);
        if (!this.isAdd && this.modelForm.serviceId) {
          this.serviceOrUrl = "0";
          this.serviceIdOrUrl = "serverId";
          this.isRequired = true;
        } else {
          this.serviceOrUrl = "1";
          this.serviceIdOrUrl = "url";
          this.isRequired = false;
        }
      }
    },
    setPageButton() {
      this.$emit("SetPageActions", this.actions);
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          let tag = this.isAdd ? "add" : "update";
          window.$http
            .post(`apis/route/${tag}`, this.modelForm)
            .then(response => {
              if (response) {
                this.$message.success({
                  content: !this.isAdd ? this.$t("module.routeManage.tip.updateSuccessfully") : this.$t("module.routeManage.tip.addSuccessfully"),
                  duration: 3
                });
                this.$emit("Close");
              }
            })
            .catch(() => {
              this.actions[0].loading = false;
              console.log(response);
            });
        } else {
          this.$message.error({
            content: this.$t("module.routeManage.tip.validateFailed"),
            duration: 3
          });
          this.actions[0].loading = false;
          return 0;
        }
      });
    },
    changeServiceOrUrl(value) {
      this.modelForm.serviceId = "";
      this.modelForm.url = "";
      debugger
      if (value === "0") {
        this.isRequired = true;
        this.serviceIdOrUrl = "serviceId";
        this.$nextTick(() => {
          // this.$refs.editForm.validateField('serviceId')
          this.$refs.editForm.fields.forEach(item => {
            if (item.prop == 'serviceId') {
              item.resetField()
            }
          })
        })

      } else {
        this.isRequired = false;
        this.serviceIdOrUrl = "url";
        this.$nextTick(() => {
          this.$refs.editForm.fields.forEach(item => {
            if (item.prop == 'url') {
              item.resetField()
            }
          })
          // this.$refs.editForm.validateField('url')
        })

      }
    }
  },
  watch: {},
  directives: {}
};
</script>


